<!DOCTYPE html>
<html lang=zh>
<head>
    <!-- so meta -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="HandheldFriendly" content="True">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="原文链接：https:&#x2F;&#x2F;juejin.im&#x2F;post&#x2F;5df6d2eaf265da33bc57db96  默认情况下，Spring 只知道如何转换简单数据类型。比如我们提交的 int、String 或 boolean 类型的请求数据，它会自动绑定到与之对应的 Java 类型。但在实际项目中，远远不够，因为我们可能需要绑定更复杂的对象类型。我们需要了解 Spring 数据绑定机制，这样我们就可以">
<meta property="og:type" content="article">
<meta property="og:title" content="使用Spring 数据绑定机制，让RESTful API代码更简洁">
<meta property="og:url" content="https:&#x2F;&#x2F;fengzxia.gitee.io&#x2F;posts&#x2F;9ef0a90d.html">
<meta property="og:site_name" content="只是学习学习的博客">
<meta property="og:description" content="原文链接：https:&#x2F;&#x2F;juejin.im&#x2F;post&#x2F;5df6d2eaf265da33bc57db96  默认情况下，Spring 只知道如何转换简单数据类型。比如我们提交的 int、String 或 boolean 类型的请求数据，它会自动绑定到与之对应的 Java 类型。但在实际项目中，远远不够，因为我们可能需要绑定更复杂的对象类型。我们需要了解 Spring 数据绑定机制，这样我们就可以">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https:&#x2F;&#x2F;img-blog.csdnimg.cn&#x2F;20191216165041867.png?x-oss-process&#x3D;image&#x2F;watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNDMwMDgz,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https:&#x2F;&#x2F;img-blog.csdnimg.cn&#x2F;20191216172234550.png?x-oss-process&#x3D;image&#x2F;watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNDMwMDgz,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2019-12-16T09:27:34.000Z">
<meta property="article:modified_time" content="2020-04-17T10:28:04.548Z">
<meta property="article:author" content="只是学习学习">
<meta property="article:tag" content="优化">
<meta property="article:tag" content="RESTful">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https:&#x2F;&#x2F;img-blog.csdnimg.cn&#x2F;20191216165041867.png?x-oss-process&#x3D;image&#x2F;watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNDMwMDgz,size_16,color_FFFFFF,t_70">
    
    
        
          
              <link rel="shortcut icon" href="/images/favicon.ico">
          
        
        
          
            <link rel="icon" type="image/png" href="/images/favicon-192x192.png" sizes="192x192">
          
        
        
          
            <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png">
          
        
    
    <!-- title -->
    <title>使用Spring 数据绑定机制，让RESTful API代码更简洁</title>
    <!-- styles -->
    
<link rel="stylesheet" href="/css/style.css">

    <!-- persian styles -->
    
      
<link rel="stylesheet" href="/css/rtl.css">

    
    <!-- rss -->
    
    
    
<meta name="generator" content="Hexo 4.1.1"></head>

<body class="max-width mx-auto px3 ltr">
    
      <div id="header-post">
  <a id="menu-icon" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="menu-icon-tablet" href="#"><i class="fas fa-bars fa-lg"></i></a>
  <a id="top-icon-tablet" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');" style="display:none;"><i class="fas fa-chevron-up fa-lg"></i></a>
  <span id="menu">
    <span id="nav">
      <ul>
         
          <li><a href="/">主页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/friend_ship/">友链</a></li>
        
      </ul>
    </span>
    <br/>
    <span id="actions">
      <ul>
        
        <li><a class="icon" href="/posts/ff99cf0e.html"><i class="fas fa-chevron-left" aria-hidden="true" onmouseover="$('#i-prev').toggle();" onmouseout="$('#i-prev').toggle();"></i></a></li>
        
        
        <li><a class="icon" href="/posts/5f51e8ee.html"><i class="fas fa-chevron-right" aria-hidden="true" onmouseover="$('#i-next').toggle();" onmouseout="$('#i-next').toggle();"></i></a></li>
        
        <li><a class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up" aria-hidden="true" onmouseover="$('#i-top').toggle();" onmouseout="$('#i-top').toggle();"></i></a></li>
        <li><a class="icon" href="#"><i class="fas fa-share-alt" aria-hidden="true" onmouseover="$('#i-share').toggle();" onmouseout="$('#i-share').toggle();" onclick="$('#share').toggle();return false;"></i></a></li>
      </ul>
      <span id="i-prev" class="info" style="display:none;">上一篇</span>
      <span id="i-next" class="info" style="display:none;">下一篇</span>
      <span id="i-top" class="info" style="display:none;">返回顶部</span>
      <span id="i-share" class="info" style="display:none;">分享文章</span>
    </span>
    <br/>
    <div id="share" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://fengzxia.gitee.io/posts/9ef0a90d.html" target="_blank" rel="noopener"><i class="fab fa-facebook " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&text=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-twitter " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-linkedin " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&is_video=false&description=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-pinterest " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=使用Spring 数据绑定机制，让RESTful API代码更简洁&body=Check out this article: https://fengzxia.gitee.io/posts/9ef0a90d.html"><i class="fas fa-envelope " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-get-pocket " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-reddit " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-stumbleupon " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-digg " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&name=使用Spring 数据绑定机制，让RESTful API代码更简洁&description=" target="_blank" rel="noopener"><i class="fab fa-tumblr " aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://news.ycombinator.com/submitlink?u=https://fengzxia.gitee.io/posts/9ef0a90d.html&t=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-hacker-news " aria-hidden="true"></i></a></li>
</ul>

    </div>
    <div id="toc">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-数据绑定"><span class="toc-number">1.</span> <span class="toc-text">Spring 数据绑定</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#日期绑定"><span class="toc-number">1.1.</span> <span class="toc-text">日期绑定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#枚举类型绑定"><span class="toc-number">1.2.</span> <span class="toc-text">枚举类型绑定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#绑定对象"><span class="toc-number">1.3.</span> <span class="toc-text">绑定对象</span></a></li></ol></li></ol>
    </div>
  </span>
</div>

    
    <div class="content index py4">
        
        <article class="post" itemscope itemtype="http://schema.org/BlogPosting">
  <header>
    
    <h1 class="posttitle" itemprop="name headline">
        使用Spring 数据绑定机制，让RESTful API代码更简洁
    </h1>



    <div class="meta">
      <span class="author" itemprop="author" itemscope itemtype="http://schema.org/Person">
        <span itemprop="name">只是学习学习的博客</span>
      </span>
      
    <div class="postdate">
      
        <time datetime="2019-12-16T09:27:34.000Z" itemprop="datePublished">2019-12-16</time>
        
      
    </div>


      
    <div class="article-category">
        <i class="fas fa-archive"></i>
        <a class="category-link" href="/categories/Java/">Java</a> › <a class="category-link" href="/categories/Java/Spring/">Spring</a> › <a class="category-link" href="/categories/%E8%BD%AC%E8%BD%BD/">转载</a>
    </div>


      
    <div class="article-tag">
        <i class="fas fa-tag"></i>
        <a class="tag-link" href="/tags/RESTful/" rel="tag">RESTful</a>, <a class="tag-link" href="/tags/%E4%BC%98%E5%8C%96/" rel="tag">优化</a>
    </div>


    </div>
  </header>
  

  <div class="content"itemprop ="articleBody">
    <blockquote>
<p>原文链接：<a href="https://juejin.im/post/5df6d2eaf265da33bc57db96" target="_blank" rel="noopener">https://juejin.im/post/5df6d2eaf265da33bc57db96</a></p>
</blockquote>
<p>默认情况下，Spring 只知道如何转换简单数据类型。比如我们提交的 <code>int</code>、<code>String</code> 或 <code>boolean</code> 类型的请求数据，它会自动绑定到与之对应的 Java 类型。但在实际项目中，远远不够，因为我们可能需要绑定更复杂的对象类型。<br>我们需要了解 Spring 数据绑定机制，这样我们就可以更灵活的做全局配置或自定义配置，进而让我们的 RESTful API 更简洁，可读性也更好。</p>
<h2 id="Spring-数据绑定"><a href="#Spring-数据绑定" class="headerlink" title="Spring 数据绑定"></a>Spring 数据绑定</h2><h3 id="日期绑定"><a href="#日期绑定" class="headerlink" title="日期绑定"></a>日期绑定</h3><p>先来看下面一小段代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(<span class="string">"/index"</span>)</span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">IndexController</span> </span>&#123;</span><br><span class="line">  <span class="meta">@GetMapping</span>(<span class="string">"/&#123;date&#125;"</span>)</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getSpecificDateInfo</span><span class="params">(@PathVariable LocalDateTime date)</span> </span>&#123;</span><br><span class="line">    log.info(date.toString());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当我们用 Postman 请求这个 API</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">localhost:8080/index/2019-12-10 12:00:00</span><br></pre></td></tr></table></figure>

<p>如我们所料，抛出数据类型转换异常</p>
<p><img src="https://img-blog.csdnimg.cn/20191216165041867.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNDMwMDgz,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>因为 Spring 默认不支持将 String 类型的请求参数转换为 <code>LocalDateTime</code> 类型，所以我们需要自定义 <code>converter 「转换器</code> 完整整个转换过程</p>
<p>自定义转换器 <code>StringToLocalDateTimeConverter</code>，使其实现 <code>org.springframework.core.convert.converter.Converter&lt;S, T&gt;</code> 接口，在重写的 <code>convert 方法</code>中实现我们自定义的转换逻辑</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringToLocalDateTimeConverter</span> <span class="keyword">implements</span> <span class="title">Converter</span>&lt;<span class="title">String</span>, <span class="title">LocalDateTime</span>&gt; </span>&#123;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> LocalDateTime <span class="title">convert</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(<span class="string">"yyyy-MM-dd HH:mm:ss"</span>, Locale.CHINESE);</span><br><span class="line">    <span class="keyword">return</span> LocalDateTime.parse(s, formatter);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>将转换器注册到上下文中:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UnifiedReturnConfig</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addFormatters</span><span class="params">(FormatterRegistry registry)</span> </span>&#123;</span><br><span class="line">    registry.addConverter(<span class="keyword">new</span> StringToLocalDateTimeConverter());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>重新访问上面链接，查看控制台，按照预期得到相应转换结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">2019-12-16 17:01:56.848  INFO 6420 --- [nio-8081-exec-3] com.lx.controller.IndexController        : 2019-12-10T12:00</span><br></pre></td></tr></table></figure>
<p>知道了这个，比如我们常用的枚举类型也可以应用这种方式做数据绑定</p>
<h3 id="枚举类型绑定"><a href="#枚举类型绑定" class="headerlink" title="枚举类型绑定"></a>枚举类型绑定</h3><p>同样的套路，自定义转换器，<code>Modes</code>为自己创建的枚举类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringToEnumConverter</span> <span class="keyword">implements</span> <span class="title">Converter</span>&lt;<span class="title">String</span>, <span class="title">Modes</span>&gt; </span>&#123;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> Modes <span class="title">convert</span><span class="params">(String s)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Modes.valueOf(s);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>将其添加至上下文，请小伙伴们自行尝试吧，知道了这个，我们再也不用在 RESTful API 内部做数据转换了，我们做到了全局控制，同时让整个 API 看起来更加清晰简洁</p>
<h3 id="绑定对象"><a href="#绑定对象" class="headerlink" title="绑定对象"></a>绑定对象</h3><p>在某些情况下，我们希望将数据绑定到对象，这时我们可能马上联想起来使用 <code>@RequestBody</code> 注解，该注解通常用于获取 POST 请求体，并将其转换相应的数据对象<br>在实际业务场景中，除了<code>请求体</code>中的数据，我们同样需要<code>请求头</code>中的数据，比如<code>token</code> ，<code>token</code> 中包含当前登陆用户的信息，每一次 RESTful 请求我们都需要从 <code>header</code> 中获取 <code>token</code> 数据处理实际业务，这种场景，上文提到的 <code>Converter</code> 以及 <code>@RequestBody</code> 显然不能满足我们的需求，此时我们就要换另一种解决方案 : <code>HandlerMethodArgumentResolver</code><br>首先我们需要自定义一个注解 <code>LoginUser</code> (<strong>运行时生效，作用于参数上</strong>)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="meta">@Target</span>(ElementType.PARAMETER)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> LoginUser &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后自定义 LoginUserArgumentResolver ，使其实现 HandlerMethodArgumentResolver 接口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LoginUserArgumentResolver</span> <span class="keyword">implements</span> <span class="title">HandlerMethodArgumentResolver</span> </span>&#123;</span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter methodParameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 判断参数是否有自定义注解 LoginUser修饰</span></span><br><span class="line">    <span class="keyword">return</span> methodParameter.hasParameterAnnotation(LoginUser<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();</span><br><span class="line">    LoginUserVo loginUserVo = <span class="keyword">new</span> LoginUserVo();</span><br><span class="line">    String token = request.getHeader(<span class="string">"token"</span>);</span><br><span class="line">    <span class="keyword">if</span> (StringUtils.isNotBlank(token)) &#123;</span><br><span class="line">      <span class="comment">//通常这里需要编写 token 解析逻辑，并将其放到 LoginUserVo 对象中,此处省略</span></span><br><span class="line">      <span class="comment">//logic</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//在此为了快速简洁的做演示说明，省略掉解析 token 部分，直接从 header 指定 key 中获取数据</span></span><br><span class="line">    loginUserVo.setId(Long.valueOf(request.getHeader(<span class="string">"userId"</span>)));</span><br><span class="line">    loginUserVo.setName(request.getHeader(<span class="string">"userName"</span>));</span><br><span class="line">    <span class="keyword">return</span> loginUserVo;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>依旧将自定义的 <code>LoginUserArgumentResolver</code> 添加到上下文中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addArgumentResolvers</span><span class="params">(List&lt;HandlerMethodArgumentResolver&gt; resolvers)</span> </span>&#123;</span><br><span class="line">  resolvers.add(<span class="keyword">new</span> LoginUserArgumentResolver());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>编写 API:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@GetMapping</span>(<span class="string">"/id"</span>)</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">getLoginUserInfo</span><span class="params">(@LoginUser LoginUserVo loginUserVo)</span> </span>&#123;</span><br><span class="line">  log.info(loginUserVo.toString());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>通过 Postman 请求，在 header 中设置好相应的 K-V，如下图</p>
<figure class="highlight http"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">localhost:8081/index/id</span></span><br></pre></td></tr></table></figure>
<p><img src="https://img-blog.csdnimg.cn/20191216172234550.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzNDMwMDgz,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>发送请求，查看控制台，得到预期结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">c.e.unifiedreturn.api.BindingController  : LoginUserVo(id&#x3D;111111, name&#x3D;rgyb)</span><br></pre></td></tr></table></figure>
<p>相信到这里，你已经了解了基本的使用</p>
<blockquote>
<p>作者：日拱一兵<br>链接：<a href="https://juejin.im/post/5df6d2eaf265da33bc57db96" target="_blank" rel="noopener">https://juejin.im/post/5df6d2eaf265da33bc57db96</a><br>来源：掘金<br>著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。</p>
</blockquote>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"28a065e3b5afee156f4f","clientSecret":"e18104d6f3219526491fc42c892ff6a26b8f3e74","repo":"blog_comment","owner":"FENG1000","admin":["FENG1000"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
    
  </div>
</article>




        
          <div id="footer-post-container">
  <div id="footer-post">

    <div id="nav-footer" style="display: none">
      <ul>
         
          <li><a href="/">主页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/friend_ship/">友链</a></li>
        
      </ul>
    </div>

    <div id="toc-footer" style="display: none">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring-数据绑定"><span class="toc-number">1.</span> <span class="toc-text">Spring 数据绑定</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#日期绑定"><span class="toc-number">1.1.</span> <span class="toc-text">日期绑定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#枚举类型绑定"><span class="toc-number">1.2.</span> <span class="toc-text">枚举类型绑定</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#绑定对象"><span class="toc-number">1.3.</span> <span class="toc-text">绑定对象</span></a></li></ol></li></ol>
    </div>

    <div id="share-footer" style="display: none">
      <ul>
  <li><a class="icon" href="http://www.facebook.com/sharer.php?u=https://fengzxia.gitee.io/posts/9ef0a90d.html" target="_blank" rel="noopener"><i class="fab fa-facebook fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://twitter.com/share?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&text=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-twitter fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.linkedin.com/shareArticle?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-linkedin fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://pinterest.com/pin/create/bookmarklet/?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&is_video=false&description=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-pinterest fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="mailto:?subject=使用Spring 数据绑定机制，让RESTful API代码更简洁&body=Check out this article: https://fengzxia.gitee.io/posts/9ef0a90d.html"><i class="fas fa-envelope fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://getpocket.com/save?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-get-pocket fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://reddit.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-reddit fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.stumbleupon.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-stumbleupon fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://digg.com/submit?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&title=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-digg fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="http://www.tumblr.com/share/link?url=https://fengzxia.gitee.io/posts/9ef0a90d.html&name=使用Spring 数据绑定机制，让RESTful API代码更简洁&description=" target="_blank" rel="noopener"><i class="fab fa-tumblr fa-lg" aria-hidden="true"></i></a></li>
  <li><a class="icon" href="https://news.ycombinator.com/submitlink?u=https://fengzxia.gitee.io/posts/9ef0a90d.html&t=使用Spring 数据绑定机制，让RESTful API代码更简洁" target="_blank" rel="noopener"><i class="fab fa-hacker-news fa-lg" aria-hidden="true"></i></a></li>
</ul>

    </div>

    <div id="actions-footer">
        <a id="menu" class="icon" href="#" onclick="$('#nav-footer').toggle();return false;"><i class="fas fa-bars fa-lg" aria-hidden="true"></i> 菜单</a>
        <a id="toc" class="icon" href="#" onclick="$('#toc-footer').toggle();return false;"><i class="fas fa-list fa-lg" aria-hidden="true"></i> 目录</a>
        <a id="share" class="icon" href="#" onclick="$('#share-footer').toggle();return false;"><i class="fas fa-share-alt fa-lg" aria-hidden="true"></i> 分享</a>
        <a id="top" style="display:none" class="icon" href="#" onclick="$('html, body').animate({ scrollTop: 0 }, 'fast');"><i class="fas fa-chevron-up fa-lg" aria-hidden="true"></i> 返回顶部</a>
    </div>

  </div>
</div>

        
        <footer id="footer">
  <div class="footer-left">
    Copyright &copy;
    
    
    2019-2020
    只是学习学习
  </div>
  <div class="footer-right">
    <nav>
      <ul>
         
          <li><a href="/">主页</a></li>
         
          <li><a href="/archives/">归档</a></li>
         
          <li><a href="/categories/">分类</a></li>
         
          <li><a href="/tags/">标签</a></li>
         
          <li><a href="/search/">搜索</a></li>
         
          <li><a href="/about/">关于</a></li>
         
          <li><a href="/friend_ship/">友链</a></li>
        
      </ul>
    </nav>
  </div>
</footer>

    </div>
    <!-- styles -->

<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">


<link rel="stylesheet" href="/lib/justified-gallery/css/justifiedGallery.min.css">


    <!-- jquery -->

<script src="/lib/jquery/jquery.min.js"></script>


<script src="/lib/justified-gallery/js/jquery.justifiedGallery.min.js"></script>

<!-- clipboard -->

  
<script src="/lib/clipboard/clipboard.min.js"></script>

  <script type="text/javascript">
  $(function() {
    // copy-btn HTML
    var btn = "<span class=\"btn-copy tooltipped tooltipped-sw\" aria-label=\"复制到粘贴板!\">";
    btn += '<i class="far fa-clone"></i>';
    btn += '</span>'; 
    // mount it!
    $(".highlight table").before(btn);
    var clip = new ClipboardJS('.btn-copy', {
      text: function(trigger) {
        return Array.from(trigger.nextElementSibling.querySelectorAll('.code')).reduce((str,it)=>str+it.innerText+'\n','')
      }
    });
    clip.on('success', function(e) {
      e.trigger.setAttribute('aria-label', "复制成功!");
      e.clearSelection();
    })
  })
  </script>


<script src="/js/main.js"></script>

<!-- search -->

<!-- Google Analytics -->

<!-- Baidu Analytics -->

    <script type="text/javascript">
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?54382acbd8c4bc66535bce135e0ac166";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>

<!-- Disqus Comments -->


</body>
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https'){
   bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
  }
  else{
  bp.src = 'http://push.zhanzhang.baidu.com/push.js';
  }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
</html>
